package com.issc.framework.helper;

import com.issc.framework.annotation.Controller;
import com.issc.framework.annotation.Service;
import com.issc.framework.util.ClassUtil;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

public class ClassHelper {
    private static Set<Class<?>> CLASS_SET;
    private static Set<Class<?>> serviceClassSet = new HashSet<>(100);
    private static Set<Class<?>> controllerClassSet = new HashSet<>(100);
    private static Set<Class<?>> beanClassSet = new HashSet<>(100);

    //获取应用包名下的所有类
    static {
        String appBasePackage = ConfigHelper.getAppBasePackage();
        CLASS_SET = ClassUtil.getClassSet(appBasePackage);
    }

    //遍历获取注解分别为（service,Controller）的类，并分别放入集合中
    static {
        for (Class<?> cls : CLASS_SET) {
            if (cls.isAnnotationPresent(Service.class)) {
                serviceClassSet.add(cls);
                beanClassSet.add(cls);
            } else if (cls.isAnnotationPresent(Controller.class)){
                controllerClassSet.add(cls);
                beanClassSet.add(cls);
            }
            else {
                beanClassSet.add(cls);
            }
        }
    }

    /**
     * 获取所应用包名下的所有类
     */
    public static Set<Class<?>> getClassSet() {
        return CLASS_SET;
    }

    /**
     * 获取应用包名下的所有Service类
     */
    public static Set<Class<?>> getServiceClassSet() {
        return serviceClassSet;
    }

    /**
     * 获取应用包名下的所有Controller类
     */
    public static Set<Class<?>> getControllerClassSet() {
        return controllerClassSet;
    }

    /**
     * 获取应用包名下的所有Bean(service、Controller等)类
     */
    public static Set<Class<?>> getBeanClassSet() {
        return beanClassSet;
    }

    //获取父类下的所有子类
    public static Set<Class<?>> getClassSetBySuper(Class<?> superClass){
        Set<Class<?>> classSet = new HashSet<>();
        for (Class<?> clz : CLASS_SET) {
            if (superClass.isAssignableFrom(clz) && !superClass.equals(clz)) {
                classSet.add(clz);
            }
        }
        return classSet;
    }
    //获取某个注解的所有类并放入集合中
    public static Set<Class<?>> getClassSetByAnnotation(Class<? extends Annotation> annotationClass) {
        Set<Class<?>> classSet = new HashSet<>();
        for (Class<?> clz : CLASS_SET) {
            if (clz.isAnnotationPresent(annotationClass)) {
                classSet.add(clz);
            }
        }
        return  classSet;
    }
}
